<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="title">登录系统</h2>
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="formRef"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            prefix-icon="User"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            prefix-icon="Lock"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            style="width: 100%"
            @click="onLogin"
            >登 录</el-button
          >
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: flex-end">
        <a href="/adminRegister">没有账号？立即注册</a>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { adminLogin } from "@/api/admin";

const loginForm = ref({
  username: "",
  password: "",
});

const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const formRef = ref();
const loading = ref(false);

const onLogin = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await adminLogin(loginForm.value);
        ElMessage.success("登录成功");
        localStorage.setItem("adminlogined", "true");
        window.location.href = "/admin";
      } catch (err) {
        // ElMessage.error("登录失败");
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #a1c4fd, #c2e9fb);
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  width: 360px;
  padding: 30px 20px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background: white;
}

.title {
  text-align: center;
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}
</style>
